<template>
  <!-- 收藏文章组件 -->
  <van-icon
    name="star"
    color="orange"
    :loading="followLoading"
    v-if="articleClloected"
    @click="collectFN"
  />
  <van-icon
    color="#777"
    name="star-o"
    :loading="followLoading"
    v-else
    @click="collectFN"
  />
</template>

<script>
import { collectArticle, dlCollectArticle } from '@/api/article'
export default {
  name: 'CollectArticle',
  data() {
    return {
      followLoading: false // loading 状态显示与否
    }
  },
  // 自定义 v-model 的数据名称
  model: {
    prop: 'articleClloected', // 默认是 value
    event: 'update-is_clloected' // 默认是 input
  },
  props: {
    // 文章Id
    articleId: {
      type: [Number, String, Object],
      required: true
    },
    // 文章收藏状态
    articleClloected: {
      type: Boolean,
      required: true
    }
  },

  methods: {
    // 收藏和取消收藏
    async collectFN() {
      this.followLoading = true
      try {
        if (this.articleClloected) {
          // 已收藏，取消收藏
          await dlCollectArticle(this.articleId)
        } else {
          await collectArticle(this.articleId)
        }
        this.$emit('update-is_clloected', !this.articleClloected)
        this.$toast.success(!this.articleClloected ? '收藏成功' : '取消收藏')
      } catch (error) {
        let message = '操作失败，请重试'
        if (error.response && error.response.status === 400) {
          message = '你不能关注你自己！'
        }
        this.$toast(message)
      }
      this.followLoading = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
